<template>
  <view class="sign-box" v-show="modelValue" :style="{height:'100vh'}">
    <view class="canvas-autograph ">
      <canvas canvasId="comCanvas" disable-scroll="true" class="pos"/>
      <canvas class="scroll-view" :canvas-id="canvasId" @touchstart="touchstart" @touchmove="touchmove"
              disable-scroll="true" @touchend="touchend"/>
      <view class="fun-box ">
        <uv-button round block type="error" size="small" @click="clear">清空</uv-button>
        <uv-button round block type="primary" size="small" @click="sign('confirm')">确认</uv-button>
        <uv-button round block type="error" size="small" @click="cancel">取消</uv-button>
        <uv-button round block type="primary" size="small" @click="sign('save')">保存签名</uv-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import api from '@/api/school/signature/signature'
import {ref, reactive, watch, getCurrentInstance, onMounted} from 'vue'

const {proxy} = getCurrentInstance();
const emits = defineEmits(['update:modelValue', 'complete'])
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  infor: {
    type: Object,
    default: {}
  },
  canvasId: {
    type: String,
    default: 'mycanvas'
  },
  tableName: {                // 签名表名
    type: String,
    default: ''
  },
  tableType: {                // 签名表名类型
    type: String,
    default: ''
  },
  required: {
    type: Boolean,
    default: true
  }
})
watch(() => props.modelValue, e => {
}, {
  immediate: true,
})
let points = ref([])
let pointList = ref([])
const isDraw = ref(false)
let canvaCtx = ref(uni.createCanvasContext(props.canvasId, proxy))
canvaCtx.value.lineWidth = 4;
canvaCtx.value.lineCap = 'round'
canvaCtx.value.lineJoin = 'round'
const touchstart = e => {
  let startX = e.changedTouches[0].x
  let startY = e.changedTouches[0].y
  let startPoint = {
    X: startX,
    Y: startY
  }
  points.value.push(startPoint);
  canvaCtx.value.beginPath();
}
const touchmove = e => {
  let moveX = e.changedTouches[0].x
  let moveY = e.changedTouches[0].y
  let movePoint = {
    X: moveX,
    Y: moveY
  }
  points.value.push(movePoint)
  pointList.value.push(movePoint)
  let len = points.value.length
  if (len >= 2) {
    draw();
  }
}
const draw = () => {
  let point1 = points.value[0]
  let point2 = points.value[1]
  points.value.shift();
  canvaCtx.value.moveTo(point1.X, point1.Y)
  canvaCtx.value.lineTo(point2.X, point2.Y)
  canvaCtx.value.stroke()
  canvaCtx.value.draw(true);
}
const touchend = e => {
  points.value = [];
}

/**
 * 临时图片路径转base64
 * @param {Object} param 传一个对象，对象里包括
 * url: 临时图片存放路径，选择图片返回的相对路径
 * type: 图片类型，如：png
 */
function base64(url, type) {
  return new Promise((resolve, reject) => {
    if (!!uni.getFileSystemManager()) {
      uni.getFileSystemManager().readFile({
        filePath: url, //选择图片返回的相对路径
        encoding: "base64", //编码格式
        success: (res) => {
          resolve(
              "data:image/" +
              type.toLocaleLowerCase() +
              ";base64," +
              res.data
          );
        },
        fail: (res) => reject(res.errMsg),
      });
    } else {
      uni.request({
        url: url,
        method: "GET",
        responseType: "arraybuffer",
        success: (ress) => {
          let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64
          base64 = "data:image/jpeg;base64," + base64; //不加上这串字符，在页面无法显示的哦
          resolve(base64);
        },
        fail: (res) => reject(res.errMsg),
      });
    }
  });
}

const isTrue = ref(true)

/** 保存签字 */
const save = (res1) => {
  // #ifdef MP-WEIXIN
  let img = base64(res1.tempFilePath, 'png');
  img.then(res2 => {
    let form = {};
    form.tableName = props.tableName;
    form.tableType = props.tableType;
    form.personSign = res2;
    proxy.http.asyncPost(api.signatureAdd, form).then(res3 => {
      if (res3.code === 0) {
        uni.showToast({icon: 'success', title: '保存成功', duration: 2000});
        emits('update:modelValue', false);
        emits('complete', res2);
      } else {
        uni.showToast({title: res3.msg, icon: 'none'});
      }
    });
  })
  // #endif
  // #ifdef H5
  let form = {};
  form.tableName = props.tableName;
  form.tableType = props.tableType;
  form.personSign = res1.tempFilePath;
  proxy.http.asyncPost(api.signatureAdd, form).then(res3 => {
    if (res3.code === 0) {
      uni.showToast({icon: 'success', title: '保存成功', duration: 2000});
      emits('update:modelValue', false);
      emits('complete', res1.tempFilePath);
    } else {
      uni.showToast({title: res3.msg, icon: 'none'});
    }
  });
  // #endif
}

/** 确认签字 */
const confirm = (res1) => {
  // #ifdef MP-WEIXIN
  let img = base64(res1.tempFilePath, 'png');
  img.then(res2 => {
    emits('update:modelValue', false);
    // getImageInfo(tempFilePath)
    emits('complete', res2);
  })
  // #endif
  // #ifdef H5
  emits('update:modelValue', false);
  emits('complete', res1.tempFilePath);
  // #endif
}

/** 签字操作 */
const sign = (operation) => {
  if (pointList.value.length < 1) {
    if(props.required){
      uni.showToast({
        icon: 'none',
        title: '请签字'
      })
    }else{
      clear();
      emits('complete', '');
    }
  } else {
    uni.canvasToTempFilePath({
      canvasId: props.canvasId,
      complete: (res) => {
        const {
          tempFilePath
        } = res
        uni.getImageInfo({
          src: tempFilePath,
          success: (res) => {
            let ctx = uni.createCanvasContext('comCanvas', proxy);
            let rate = res.height / res.width
            let width = 300 / rate
            let height = 300
            ctx.clearRect(-width / 2, -height / 2, width, height);
            ctx.draw(true);
            if(isTrue.value){
              ctx.translate(height / 2, width / 2)
              ctx.rotate((270 * Math.PI) / 180)
              isTrue.value = false
            }
            ctx.drawImage(res.path, -width / 2, -height / 2, width, height)
            ctx.draw(true,function(){
              uni.canvasToTempFilePath({
                canvasId: 'comCanvas',
                complete: (res1) => {
                  if(operation == 'confirm'){
                    confirm(res1);
                  } else {
                    save(res1);
                  }
                  clear();
                }
              }, proxy)
            })
          }
        })
      }
    }, proxy)
  }
}

/** 清空按钮 */
const clear = () => {
  pointList.value = []
  return uni.getSystemInfo()
      .then(res => {
        canvaCtx.value.clearRect(0, 0, res.windowWidth, res.windowHeight);
        canvaCtx.value.draw(true);
        return res
      })
      .catch(err => {
        console.log(err);
      })
}

/** 取消按钮 */
const cancel = () => {
  pointList.value = []
  clear().then((res) => {
    emits('update:modelValue', false);
  })
}
</script>

<style scoped lang="scss">
.sign-box {
  position: fixed;
  width: 100vw;
  bottom: 0;
  left: 0%;
  z-index: 998;
  background: #e7e7e7;
  border-radius: 30rpx;
}

.canvas-autograph {
  position: absolute;
  z-index: 998;
  height: 95%;
  width: 82%;
  top: 50%;
  left: 50%;
  transform: translate(-43%, -50%);

  .scroll-view {
    width: 100%;
    height: 100%;
    background-color: #FFFFFF;
    position: absolute!important;
    top: 0;
    right: 0;
  }

  .fun-box {
    position: absolute;
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    transform: rotate(90deg);
    top: 50%;
    left: -59%;

    .fun-box-btn {
      width: 160rpx;
      height: 100%;
      color: #FFFFFF;
      border-radius: 20rpx;
      border: 1rpx solid #C0C0C0;
      text-align: center;

      + .fun-box-btn {
        margin-left: 20rpx;
      }
    }
  }
}
.pos {
  position: absolute;
  opacity: 0;
}
/* #ifndef H5 */
.pos {
  position: absolute;
  left: -300rpx;
  top: -300rpx;
}
/* #endif */
</style>